package com.bdqn.t330.ch12file.servcie;

import com.bdqn.t330.ch12file.entity.Role;
import com.bdqn.t330.ch12file.entity.User;
import com.bdqn.t330.ch12file.repository.UserRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImp implements UserService {

    @Resource
    UserRepository userRepository;

    @Override
    public List<User> loginService(String usrName, String usrPassword) {
        return userRepository.findByUsrName(usrName);
    }

    @Override
    public User findByUsrNameBiz(String usrName) {
        if (userRepository.findByUsrName(usrName).size() > 0) {
            return userRepository.findByUsrName(usrName).get(0);
        } else {
            return null;
        }

    }

    @Override
    public Page<User> getListService(Map<String, Object> param, Pageable pageable) {
        return userRepository.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (param.get("usrName") != null && param.get("usrName").toString().length() > 0) { //动态 SQL
                    predicates.add(criteriaBuilder.like(root.get("usrName"), "%" + param.get("usrName") + "%"));
                }
                if (!param.get("roleId").equals("0") && Long.valueOf(param.get("roleId").toString()) > 0) { //动态 SQL
                    //predicates.add(criteriaBuilder.equal(root.get("roleId"), param.get("roleId")));
                    Role role = new Role();
                    role.setRoleId(Long.valueOf(param.get("roleId").toString()));
                    predicates.add(criteriaBuilder.equal(root.get("role"), role));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        }, pageable);
    }

    @Override
    public User saveService(User user) {
        return userRepository.save(user);
    }

    @Override
    public void deleteUserService(Long usrId) throws Exception {
        userRepository.deleteById(usrId);
    }

    public User findByUserIdService(Long usrId) {
        return userRepository.findById(usrId).get();
    }
}
